-- Copyright (c) 2024 Huawei Technologies Co., Ltd.
-- openUBMC is licensed under Mulan PSL v2.
-- You can use this software according to the terms and conditions of the Mulan PSL v2.
-- You may obtain a copy of Mulan PSL v2 at: http://license.coscl.org.cn/MulanPSL2
-- THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
-- EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
-- MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
-- See the Mulan PSL v2 for more details.

local device_object = require 'mc.mdb.device_tree.device_object'
local log = require 'mc.logging'
local ctx = require 'mc.context'

local fans = device_object('Fans')

function fans:ctor()
    self.fan_max_num = 8
end

function fans:set_fans_pwm(l_pwm)
    if #l_pwm ~= self.fan_max_num then
        log:info('wrong pwm number.')
        return 1
    end

    for index = 1, self.fan_max_num, 2 do
        -- 相邻风扇取第二个风扇转速
        l_pwm[index] = l_pwm[index + 1]
    end
    -- 批量下发转速前先下发设置一遍期望转速
    for index = 1, self.fan_max_num do
        local fan_object = self:get_dev_object('Fan_' .. index)
        fan_object:set_fan_expected_pwm(l_pwm[index])
    end
    log:debug(l_pwm)

    local send_data = string.pack(string.rep('B', self.fan_max_num), table.unpack(l_pwm))
    local ok, resp = pcall(function()
        return self.PWMChip:Write(ctx.get_context_or_default(), self.SetPWMCmd, send_data)
    end)
    if not ok then
        log:info('set fans failed, resp: %s', resp)
        return 1
    end

    return 0
end

function fans:init()
    self:declare_method('Fans', 'bmc.dev.Fans', 'SetFansPWM', function (...)
        return self:set_fans_pwm(...)
    end)
end

return fans